package command

import (
	"errors"
	"fmt"
	"net"
	"os"
	"os/exec"
)

type VLC string

var (
	ARGERR = errors.New("Number of args is not right! Must be:source,port,name")
)

func NewVLC() VLC {
	var vlc VLC = "vlc"
	return vlc
}

//获取本机的ip地址
func getIP() (string, error) {
	addrs, err := net.InterfaceAddrs()
	if err != nil {
		return "", err
	}
	ip := addrs[0].String()
	return ip, nil
}

//参数为三个，source，port，name
func (v *VLC) Start(args ...string) (res result, err error) {
	if len(args) != 3 {
		err = ARGERR
		return
	}

	arg1 := "-vvv"
	arg2 := args[0]
	arg3 := "--sout"
	arg4 := fmt.Sprintf("#rtp{sdp=rtsp://:%s/%s}", args[1], args[2])

	cmd := exec.Command(string(*v), arg1, arg2, arg3, arg4)
	err = cmd.Start()
	if err != nil {
		return
	}
	ip, _ := getIP()
	res.Out = fmt.Sprintf("rtsp://%s:8554/%s", ip, args[2])
	res.Pid = cmd.Process.Pid
	return
}

func (v *VLC) Stop(pid int) error {
	pro := os.Process{Pid: pid}
	err := pro.Kill()
	//当出现错误，并且错误不是进程不存在的话，返回错误
	if err != nil && err != os.ErrNotExist {
		return err
	}
	return nil
}
